<template>
    <div class="user-info">
        <pub-top isBorder="true" title="个人资料"></pub-top>

        <!-- 头像 -->
        <div class="user-img-box flex jus-b ali-c">
            <span class="user-img-name">头像</span>
            <div class="user-img flex" @click="onUploader">
                <img :src="data.avatar" alt="">
            </div>
        </div>

        <!-- 详细信息 -->
        <div class="user-detail-infos flexv mt2">
            <div class="user-nickname flex">
                <router-link :to="'/changeName'" class="flex1 flex jus-b">
                    <span>昵称</span><input class="flex1" type="text" readonly placeholder="设置个性昵称" :value="data.nickname" />
                </router-link>
                </div>
            <div class="user-nickname flex">
                <router-link :to="'/binding'" class="flex1 flex jus-b">
                    <span>手机号</span><input class="flex1" type="text" readonly placeholder="请绑定手机号" :value="data.mobile" />
                </router-link>
            </div>
            <div class="user-nickname flex jus-b"><span>性别</span><input class="flex1" @click="onSexClick" type="text" readonly placeholder="请设置" :value=" data.sex == 0 ? '女' : '男'" /></div>
            <div class="user-nickname flex jus-b"><span>生日</span><input class="flex1" @click="setBir" type="text" readonly placeholder="请设置" :value="data.birthday" /></div>
        </div>


        <!-- 性别选择  -->
        <van-actionsheet v-model="isSex" :actions="actions" cancel-text="取消" />

        <!-- 弹窗 -->
        <van-popup v-model="show" position="bottom" :overlay="true">
            <van-datetime-picker v-model="currentDate" type="date" :min-date="minDate" @confirm="confirm" @change="change" @cancel="cancel" title="出生日期" />
        </van-popup>

    </div>
</template>
<script>
import Vue from 'vue';
import { mapState } from 'vuex';
import Qs from 'qs';
import pubTop from '@/components/top'
import wx from 'we-jssdk'; // 导入jssdk
import { Toast, DatetimePicker, Actionsheet,Popup } from 'vant';
Vue.use(DatetimePicker).use(Actionsheet).use(Popup).use(Toast)
export default {
    data(){
        return{
            data: [], // 信息
            minDate: new Date(1970, 0, 1),
            currentDate: new Date(),
            date: null,//选择的日期
            birthday: null, // 生日
            show: false,
            isSex: false,
            actions: [
                {
                    name: '男',
                    sex: 1,
                    callback: this.onClick
                },
                {
                    name: '女',
                    sex: 0,
                    callback: this.onClick
                }
            ],
            localIds: null,
            headimg: null,
            signPackage: []
        }
    },
    created(){
        Toast.loading('请稍后...')
        this.axios.get('http://jxjq.0791jr.com/index.php?m=App&c=Mine&a=person_info', {
            params: {
                uid: this.$store.state.user.uid
            }
        }).then(res => {
            if(res.status == 200){
                const data = res.data.data
                this.data = data
                Toast.clear();
            }
        })
    },
    computed: {
        ...mapState(['user'])
    },
    components: {
        pubTop,
    },
    methods: {
        onUploader(){//更换头像
            this.axios.get('http://jxjq.0791jr.com/index.php?m=App&c=Mine&a=getSignPackage',  {
                params:{
                    uid: this.$store.state.user.uid,
                    url: window.location.href.split('#')[0]
                }
            }).then(res => {
                this.signPackage = res.data.data.signPackage;
                wx.config({
                    debug: true, // 开启调试模式
                    appId: this.signPackage.appId, // 必填，公众号的唯一标识
                    timestamp: this.signPackage.timestamp, // 必填，生成签名的时间戳
                    nonceStr: this.signPackage.nonceStr, // 必填，生成签名的随机串
                    signature: this.signPackage.signature, // 必填，签名，见附录1
                    jsApiList: [
                        'chooseImage',//拍照或从手机相册中选图接口
                        'uploadImage'
                    ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                });

                wx.ready(() => {
                    // 返回选定照片的本地ID
                    wx.chooseImage({
                        count: 1, // 默认9
                        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                        success:(res)=> {
                            this.localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            // 上传图片
                            wx.uploadImage({
                                localId: this.localIds.pop(), // 需要上传的图片的本地ID，由chooseImage接口获得
                                isShowProgressTips: 1,// 默认为1，显示进度提示
                                success:(res)=> {
                                    this.headimg = res.serverId; // 返回图片的服务器端ID
                                    //传后台    
                                    var obj={
                                        uid : this.user.uid,
                                        media_id: this.headimg
                                    }
                                    this.axios.post('http://jxjq.0791jr.com/index.php?m=App&c=Mine&a=set_photo', Qs.stringify(obj),{
                                        headers:{
                                            'Content-Type' : 'application/x-www-form-urlencoded'
                                        }
                                    }).then(res => {
                                        if (res.status == 200) {
                                            if (res.data.code == 200) {
                                                this.data.avatar=res.data.data;
                                                // 存取sessionStorage的user
                                                let userInfo = JSON.parse(sessionStorage.getItem('user'));
                                                userInfo.avatar=res.data.data;
                                                sessionStorage.setItem('user', JSON.stringify(userInfo));
                                                Toast('头像更换成功');
                                            } else{
                                                Toast(res.data.msg);
                                            }
                                            
                                        }  
                                        
                                    })
                                }
                            });
                        }
                    });
                    
                });
                wx.error(function(res){
                    // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
                    // alert(res)
                });


            })
        },
        setBir(){
            this.show = true;
        },
        onSexClick() {
            this.isSex = true
        },
        onClick(item) {//性别选择
            this.paraSex = item.name;
            this.isSex = false;
            this.axios.get('http://jxjq.0791jr.com/index.php?m=App&c=Mine&a=setting', {  
                params : { //请求参数  
                    uid : this.$store.state.user.uid,
                    val: item.sex,
                    type:2
                }  
            }).then(res => {
                if (res.status == 200&&res.data.code==200) {
                    Toast('设置成功');
                    this.data.sex = item.sex;
                    // 存取sessionStorage的user
                    let userInfo = JSON.parse(sessionStorage.getItem('user'));
                    userInfo.sex=this.paraSex;
                    sessionStorage.setItem('user', JSON.stringify(userInfo));
                }else{
                    Toast(res.data.msg);
                }
            }) 
        },
        confirm(){
            if(!this.date){
                this.birthday = new Date().toLocaleDateString();
            }else {
                this.birthday = this.date.join('-');
            }
            this.axios.get('http://jxjq.0791jr.com/index.php?m=App&c=Mine&a=setting', {
                params: {
                    uid: this.$store.state.user.uid,
                    type: 3,
                    val: this.birthday
                }
            }).then(res => {
                if(res.data.code == 200){
                    Toast({
                        duration: 1800,
                        message: res.data.msg
                    })
                    this.show = false;
                    this.data.birthday = this.birthday;

                    // 存取sessionStorage的user
                    let userInfo = JSON.parse(sessionStorage.getItem('user'));
                    userInfo.birthday=this.birthday;
                    sessionStorage.setItem('user', JSON.stringify(userInfo));
                }else {
                    Toast({
                        duration: 1800,
                        message: res.data.msg
                    })
                }
            })
        },
        change(e){
            this.date = e.getValues();
        },
        cancel(){
            this.show = false;
        }
    }
}
</script>
<style lang="less" scoped>
.user-info {
    min-height: 100vh;
    background-color: #f0f0f0;
    .user-img-box {
        width: 100%;
        height: 1.5rem;
        padding: 0 0.3rem;
        background-color: #fff;
        .user-img-name {
            font-size: 0.3rem;
            line-height: 120%;
            color: #333;
        }
        .user-img {
            width: 1.1rem;
            height: 1.1rem;
            margin:  auto 0;
            border-radius: 100%;
            border: 1px solid #c7c7c7;
            overflow: hidden;
        }
    }

    // 详细信息
    .user-detail-infos {
        font-size: 0.3rem;
        line-height: 0.95rem;
        color: #333;
        .user-nickname {
            width: 100%;
            height: 0.95rem;
            padding: 0 0.3rem;
            border-bottom: 1px solid #dedede;
            background-color: #fff;
            input{
                padding-right: 0.3rem;
                text-align: right;
                background: url('~@/assets/to.png') no-repeat right center;
                background-size: 0.12rem 0.24rem;
            }
        }
    }
}
</style>
